package com.yun.many.auth.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.many.auth.dao.entity.User;
import com.yun.many.auth.dao.enums.UserStatusEnum;
import com.yun.many.auth.dao.service.IUserRepository;
import com.yun.many.auth.model.dto.LoginUser;
import com.yun.many.auth.model.req.UserEditReq;
import com.yun.many.auth.model.req.UserQueryReq;
import com.yun.many.auth.model.resp.UserVo;
import com.yun.many.auth.model.translator.UserTranslator;
import com.yun.many.auth.service.IUserService;
import com.yun.many.spec.enums.ResultCode;
import com.yun.many.spec.exception.ExceptionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements IUserService {
    private final IUserRepository userRepository;

    @Override
    public Page<UserVo> pageUser(UserQueryReq req) {
        Page<User> userPage = userRepository.pageUser(req);
        return UserTranslator.toVo(userPage);
    }

    @Override
    public Boolean save(UserEditReq req) {
        User user = UserTranslator.toEntity(req);
        return userRepository.saveOrUpdate(user);
    }

    @Override
    public LoginUser loadUserByUsername(String username) {
        User user = userRepository.getByUsername(username);
        if (Objects.isNull(user)) {
            return null;
        }
        return UserTranslator.toLoginUser(user);
    }

    @Override
    public Boolean delete(UserQueryReq req) {
        List<Long> ids = req.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            log.warn("IUserService.delete ids is empty");
            return true;
        }

        return userRepository.delete(ids);
    }

    @Override
    public Boolean frozen(UserQueryReq req) {
        Long id = req.getId();
        Integer status = req.getStatus();

        if (Objects.isNull(id) || Objects.isNull(status)) {
            ExceptionUtils.throwException(ResultCode.PARAM_EXCEPTION);
        }
        UserEditReq editReq = new UserEditReq();
        editReq.setId(id);
        editReq.setStatus(UserStatusEnum.of(status));
        return save(editReq);
    }
}
